#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <network.h>

NETWORK_ERR startSocket(int *sock){

  struct sockaddr_in address;
  char echoBuffer[RCVBUFSIZE];

  if (((*sock) = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
    return NETWORK_SOCKET_ERROR;

  address.sin_family = AF_INET;
  address.sin_addr.s_addr = INADDR_ANY;
  address.sin_port = htons(10212);
  
  if(bind((*sock),(struct sockaddr *)&address,sizeof(address)) != 0)
    return NETWORK_SOCKET_ERROR;

  if(listen((*sock), 1) < 0)
    return NETWORK_SOCKET_ERROR;

    return NETWORK_OK;
}

NETWORK_ERR acceptConnection(int sock, int *new_sock){

  int addrLen = sizeof(struct sockaddr_in);
  (*new_sock) = accept(sock, (struct sockaddr *)&address, &addrLen);
  if((*new_sock) < 0)
    return NETWORK_ACCEPT_ERROR;

  return NETWORK_OK;

}

NETWORK_ERR listenSocket(int new_sock, int *bytesRcvd, char *echoBuffer){

  (*bytesRcvd) = recv(new_sock, echoBuffer, RCVBUFSIZE, 0);
  return NETWORK_OK;

}

NETWORK_ERR closeSocket(int sock){

  close(sock);
  return NETWORK_OK;

}

NETWORK_ERR sendResponse(int sock, char *msg, int msgLen){

  if(write(sock, msg, msgLen) != msgLen){
    return NETWORK_SEND_ERROR;
  }

  return NETWORK_OK;

}
